import adminApi from '@/api/adminApi'
import { getToken, setToken, removeToken, setUserInfo } from '@/utils/auth'
import { MessageBox, Message } from 'element-ui'
// import { resetRouter } from '@/router'
import Cookies from 'js-cookie'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, verification } = userInfo
    let base_64_pwd = window.btoa(username + ':' + password);
    localStorage.setItem('user_login', base_64_pwd)
    return new Promise((resolve, reject) => {
      adminApi.authentication({
        sms_code: verification
      }).then(response => {
        const { data } = response
        console.log(response, "登录 store")
        if (response.code == '200') {
          let userInfo = {
            avatar: data.image_url,
            nickName: data.user_name,
            cityName: data.area,
            phone: data.user_phone,
            userid: data.user_uuid,
            role_id: data.role_id,
            position: data.position,
            position_id: data.position_id,
            loginTime: Date.parse(new Date()) / 1000
          }
          setUserInfo(userInfo);
          resolve(response);
          commit('SET_TOKEN', data.token);
          setToken(data.token);
        } else {
          Message({
            type: 'warning',
            message: response.message
          })
          reject(response);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },


  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve();
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

